package com.jack.xiaoer.config;

import com.jack.xiaoer.web.interceptor.AuthorizationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import java.io.IOException;

/**
 * @author JackarooZhang
 * @date 2018/6/18 10:32
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.jack.xiaoer.web") // 配置Web相关的Bean的扫描路径
@ImportResource({"classpath:spring-web.xml"}) // 引入XML配置
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthorizationInterceptor())
                .addPathPatterns("/cart/**", "/order/**");
        super.addInterceptors(registry);
    }

    /**
     * 配置Spring未拦截请求交给默认Servlet处理
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        super.configureDefaultServletHandling(configurer);
        configurer.enable();
    }

    /**
     * 配置视图
     * @return
     */
    @Bean
    public ViewResolver viewResolver() {
        // 配置视图解析器，这种视图解析器一般用于解析JSP
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        // 视图文件前缀
        resolver.setPrefix("/WEB-INF/views/");
        // 视图文件后缀
        resolver.setSuffix(".jsp");
        // 设置是否所有的Spring上下文的Bean，都可以作为Request的属性，被Jstl访问到
        resolver.setExposeContextBeansAsAttributes(true);
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    /**
     * 文件上传
     * @return
     * @throws IOException
     */
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        // 高版本的Spring和Servlet容器中使用此方式，不需要导入第三方依赖
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxUploadSize(10 * 1024 * 1024);
        resolver.setDefaultEncoding("UTF-8");
        resolver.setResolveLazily(true);
//        StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
        return resolver;
    }


}
